<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="KEY" prop="key">
        <el-input
          v-model="queryParams.key"
          placeholder="请输入流程KEY"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属分类" prop="name">
        <el-input
          v-model="queryParams.category"
          placeholder="请输入所属分类"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
          type="primary"
          icon="el-icon-upload"
          size="mini"
          @click="handleUpload"
        >部署流程定义</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-show="false">
      <el-col :span="1.5">
        <span style="color: red; font-size: 12px;">（查看流程图模糊时，可选择 .bpmn 和 .png 一同打成 zip 包部署）</span>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="definitionList">
      <!--<el-table-column type="selection" align="left" width="55" />-->
      <el-table-column label="流程定义ID" align="left" prop="id" width="250" />
      <el-table-column label="KEY" align="left" prop="key" width="150" />
      <el-table-column label="名称" align="left" prop="name" width="200" />
      <el-table-column label="版本" align="left" prop="version" width="90" />
      <el-table-column label="所属分类" align="left" prop="category" width="120" />
      <el-table-column label="部署时间" align="left" prop="deploymentTime" width="180" />
      <el-table-column label="状态" align="left" prop="suspendStateName" width="90" />
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-picture"
            @click="handleDiagram(scope.row)"
          >流程图</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleShowForm(scope.row)"
          >表单</el-button>

          <el-dropdown style="margin-left: 10px;">
            <el-button type="text" size="mini">
              更多操作<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="handleStart(scope.row)" icon="el-icon-caret-right">测试启动</el-dropdown-item>
              <el-dropdown-item
                size="mini"
                type="text"
                icon="el-icon-refresh"
                @click.native="handleConvert(scope.row)"
              >转模型</el-dropdown-item>
              <el-dropdown-item
                size="mini"
                type="text"
                icon="el-icon-sort"
                @click="handleState(scope.row)"
              >{{ scope.row.suspendState === '2' ? '激活' : '挂起' }}</el-dropdown-item>
              <el-dropdown-item @click.native="handleDelete(scope.row)" divided icon="el-icon-delete">
                删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 部署流程定义对话框 -->
    <el-dialog :title="deploy.title" :visible.sync="deploy.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xml"
        :headers="deploy.headers"
        :action="deploy.url"
        :disabled="deploy.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xml”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handelConfirm">确 定</el-button>
        <el-button @click="deploy.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="流程图查看" :visible.sync="open" width="1000px" append-to-body>
      <div style="width: 100%; text-align: center;">
        <el-image
          :src="src"
          :preview-src-list="srcList"
        />
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: right;">
        <el-button @click="close">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
    import {
        convert2Model,
        delDefinition,
        listDefinition,
        startDefinition,
        suspendOrActiveDefinition
    } from "@/api/activiti/definition.js"
    import {format} from "@/utils/activiti/myUtil.js"
    import {getToken} from '@/utils/auth'

    export default {
    name: "Definition",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 流程定义表格数据
        definitionList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 日期范围
        dateRange: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          key: undefined,
          name: undefined,
          category: undefined,
        },
        // 表单参数
        form: {}
        ,src: undefined
        ,srcList: [],
          deploy: {
            open: false,
            title: "",
            // 是否禁用上传
            isUploading: false,
            updateSupport: 0,
            // 设置上传的请求头部
            headers: { Authorization: "Bearer " + getToken() },
            // 上传的地址
            url: process.env.VUE_APP_BASE_API + '/activiti/activiti/definition/upload'
          }
      };
    },
    created() {
      this.getList();
      this.token = getToken();
    },
    methods: {
      /** 查询流程定义列表 */
      getList() {
        this.loading = true;
        listDefinition(this.queryParams).then(
          response => {
            this.definitionList = response.rows;
            this.definitionList.forEach(row => {
              row.deploymentTime = format(row.deploymentTime, 'yyyy-MM-dd HH:mm:ss');
            });
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleUpload() {
        this.deploy.open = true;
        this.deploy.title = "部署流程定义";
      },
      onOpen() {},
      onClose() {
        this.$refs['elForm'].resetFields()
      },
      close() {
        this.open = false;
      },
      /** 激活挂起按钮操作 */
      handleState(row) {
        const pid = row.id;
        const suspendState = row.suspendState;
        const opt = row.suspendState === '2' ? '激活': '挂起';
        this.$confirm('是否确认' + opt + 'ID为"' + pid + '"的流程定义?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          const data = { "procDefId": pid, "suspendState": suspendState };
          return suspendOrActiveDefinition(data);
        }).then(response => {
          this.msgSuccess("操作成功");
          this.getList();
        }).catch(function () {
        });
      },
      /** 流程图预览 */
      handleDiagram: function(row) {
          this.src = process.env.VUE_APP_BASE_API+'/activiti/activiti/definition/diagram/' + row.id;
          this.srcList = [];
          this.srcList.push(this.src);
          this.open = true;
      },
      /** 转模型按钮操作 */
      handleConvert(row) {
        const pid = row.id;
        this.$confirm('是否确认将ID为"' + pid + '"的流程定义转换成流程模型?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          const data = { "processDefinitionId": pid };
          return convert2Model(data);
        }).then(response => {
          this.msgSuccess("操作成功");
          this.getList();
        }).catch(function () {
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const deploymentId = row.deploymentId;
        this.$confirm('是否确认删除ID为"' + deploymentId + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delDefinition(deploymentId);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {
        });
      },
        /** 测试发起按钮操作 */
        handleStart (row) {
            this.$confirm('是否发起一个流程 "' + row.name + '"?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return startDefinition(row.key, row.version, {
                    businessKey: "9527"
                    , title: "测试发起"
                    , variables: {
                        text1: "这是一个测试变量"
                    }
                });
            }).then((res) => {
                this.getList();
                this.msgSuccess("发起成功");
            }).catch(function () {
            });
        },
        /** 跳转页面 */
        handleShowForm(row) {
            this.$router.push("/openform/json/" + row.deploymentId);
        },
        handelConfirm() {
            this.$refs.upload.submit();
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.deploy.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.deploy.open = false;
            this.deploy.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
            this.getList();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        }
    },
  }
</script>

<style scoped>

</style>
